<?php

/**
 * Error Controller
 *
 * @author Nguyen Hai Ha
 * @version 1.0
 */

class Error_ErrorController extends Zend_Controller_Action {

	protected $_baseUrl;
	protected $_contextPath;
	protected $_utilities;
	protected $_log_name;
	protected $_logger;

	public function init() {
		$this->_baseUrl = $this->_request->getBaseURL ();
		$this->_contextPath = "error";

		$this->view->assign ( "baseUrl", $this->_baseUrl );
		$this->view->assign ( "contextPath", $this->_contextPath );

		$this->_utilities = new Utilities ( );
		$this->view->assign ( "utilities", $this->_utilities );

		/* Check log file size and create new log file. */
		$log_name = Constant::LOG_FILE_NAME;
		$log_path = $_SERVER ['DOCUMENT_ROOT'] . $this->_baseUrl . "/app/tmp/logs/";
		$this->_log_name = $log_path . $log_name;
		$new_name = $log_path . date ( 'Ymd' ) .  '_backup' . '.log';
		$size = filesize($this->_log_name)/(1024*1024);
		if ( Constant::LOG_FILE_SIZE < $size ){
			/** Neu file da ton tai thi xoa file do. */
			if (file_exists($new_name))
				unlink($new_name);
			/** Doi ten file log hien tai va tao mot file log moi. */
			if (rename ( $this->_log_name, $new_name )){
				$handle = fopen ( $this->_log_name, "a" );
				fclose ( $handle );
			}
		}

		/* Khoi tao logger. */
		Zend_Loader::loadClass ( 'Zend_Log' );
		Zend_Loader::loadClass ( 'Zend_Log_Writer_Stream' );
		$writer = new Zend_Log_Writer_Stream ( $this->_log_name );
		$this->_logger = new Zend_Log ( $writer );
	}

	public function errorAction() {
		$errors = $this->_getParam ( 'error_handler' );

		if (is_object ( $errors )) {
			/* Neu co loi xay ra.
			 Ghi thong bao loi vao log file */
			$ex = $errors->exception;
			$this->_logger->debug ( $ex->getMessage () );

			// Clear previous content.
			$this->getResponse ()->clearBody ();
			switch ($errors->type) {
				case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER :
				case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION :
				default :
					$this->render ( "error" );
					break;
			}
			return;

		} else {
			if (! Zend_Auth::getInstance ()->hasIdentity ()) {
				$errors = 'Error: Access denied - Require login.';
				/* Write log message to log file. */
				$this->_logger->debug ( $errors );

				$this->_redirect ( "/account" );
			} else {
				$user_name = Zend_Auth::getInstance ()->getIdentity ()->usr_mobile;
				$errors = 'Error: Access denied for this acccount: ' . $user_name;
				/* Write log message to log file. */
				$this->_logger->debug ( $errors );

				$this->render ( "denied" );
			}
		}
		// Shutdown log writers.
		$this->_logger->__destruct ();
	}

}// End class.